﻿using System;
using System.IO;
using System.Threading;

namespace InDepth2Demo.Chapter5
{
    /// <summary>
    /// 5.2 方法组转换
    /// </summary>
    public class MethodGroupConversion
    {
        void MyMethod() { }
        void MyMethod(object sender, EventArgs e) { }

        public void Call()
        {
            //在向一个Threadstart或者一个EventHandler赋值时，可以将 MyMethod 作为方法组使用:
            ThreadStart x = MyMethod;
            EventHandler y = MyMethod;

            SortAndShowFiles("Sort by name", delegate (FileInfo f1, FileInfo f2) { return f1.Name.CompareTo(f2.Name); });
            SortAndShowFiles("Sort by Length", delegate (FileInfo f1, FileInfo f2) { return f1.Length.CompareTo(f2.Length); });
        }

        // 5.3 协变性和逆变性 5.4 使用匿名方法的内联委托操作
        //委托
        // Action
        // Predicate
        // Comparison

        /// <summary>
        /// 按不同的规则排序C盘文件信息
        /// </summary>
        /// <param name="title">规则，给自己看的文字</param>
        /// <param name="sortOrder">委托，排序规则</param>
        static void SortAndShowFiles(string title, Comparison<FileInfo> sortOrder)
        {
            FileInfo[] files = new DirectoryInfo(@"C:\").GetFiles();

            Array.Sort(files, sortOrder);
            Console.WriteLine(title);
            foreach (var item in files)
            {
                Console.WriteLine("{0}({1}bytes)", item.Name, item.Length);
            }

        }
    }
}
